const db = require("../db/index")
const bcrypt = require("bcryptjs");
// 获取用户信息
exports.getUserInfo = (req, res) => {
    const sql = 'select id,username,nickname,email,user_pic from ev_user where id=?'
    db.query(sql, req.user.id, (err, result) => {
        if (err) return res.send({
            status: 1,
            message: "获取用户信息失败！"
        })
        if (result.length !== 1) {
            return res.cc("获取用户信息失败！")
        }
        res.send({
            status: 200,
            message: "获取用户信息成功！",
            data: result[0]
        })
    })
    console.log("req.user:", req.user);
}

// 更新用户信息
exports.updateUserInfo = (req, res) => {
    console.log("req.body:", req.body);
    const sql = 'update ev_user set ? where id=?'
    db.query(sql, [req.body, req.user.id], (err, result) => {
        if (err) return res.send({
            status: 1,
            message: "更新用户信息失败！"
        })
        if (result.affectedRows !== 1) {
            return res.cc("更新用户信息失败！")
        }
        res.send({
            status: 200,
            message: "更新用户信息成功！"
        })
    })
}
// 重置密码
exports.updatePwd = (req, res) => {
    const sql = 'select * from ev_user where id=?'
    db.query(sql, req.user.id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc("用户不存在！")
            // console.log(req.body)

        const oldpassword = req.body.oldpassword
         const compareResult = bcrypt.compareSync(req.body.oldpassword,result[0].password) 
         if(!compareResult) return res.cc("原密码错误！")

        const newpassword = bcrypt.hashSync(req.body.newpassword,10)
        const sql2 = 'update ev_user set password=? where id=?'
        db.query(sql2,[newpassword,req.user.id],(err,result)=>{
        if(err) 
            return res.cc(err)
        if(result.affectedRows !== 1)
            return res.cc("重置密码失败！")

        res.cc("重置密码成功！",200)
        })

           
    })


}

// 更新头像
exports.updateAvatar = (req,res)=>{
    const sql = 'update ev_user set user_pic=? where id=?'
    db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err)
      
        // 执行 SQL 语句成功，但是影响行数不等于 1
        if (results.affectedRows !== 1) return res.cc('更新头像失败！')
      
        // 更新用户头像成功
        return res.cc('更新头像成功！', 200)
      })
      
}
